class AppView extends React.Component {
    constructor(props) {
        super(props);
        this.typeCode = $.query.get("typeCode");
        this.isManyNode = $.query.get("isManyNode");
        this.isAdmin = parent.hasRoles('admin');
        this.state = {
            nodeInfo: '',
            childCodeList: '',
            tblIndex: 0,
            inputValue: {},
            customInputValue: {},
            customSelectValue: {}
        }
    }

    componentDidMount() {
        layui.use(['form', 'laypage', 'upload', 'element'], () => {
            this.element = layui.element();
            this.form = layui.form();
            if (!this.isManyNode) {
                this.queryNodeInfo(this.typeCode);
            } else {
                let param = {};
                param.typeCode = this.typeCode;
                postJson("/cms/appResource/queryChildNodeInfo.x", $.param(param), (data) => {
                    const nodeInfos = data.data;
                    if (nodeInfos[0].nodePrivateInfo && nodeInfos[0].nodePrivateInfo.aliases) {
                        this.state.inputValue.nodeAliase = nodeInfos[0].nodePrivateInfo.aliases;
                    } else {
                        this.state.inputValue.nodeAliase = nodeInfos[0].resourceType.type_name;
                    }
                    this.setState({
                        childCodeList: nodeInfos,
                        nodeInfo: nodeInfos[0]
                    }, () => {
                        //通知layui初始化完成,这里是在节点信息获取完成后在会掉
                        this.refs.contentRecorded.initComplete(nodeInfos[0]);
                        this.refs.contentList.layuiInitComplete();
                        this.refs.contentDistribution.layuiInitComplete();
                    });
                });
            }
            this.element.on('tab(mainTab)', (data) => {
                this.state.tblIndex = data.index;
                if (this.state.tblIndex === 1) {
                    this.refs.contentList.queryList(1);
                } else if (this.state.tblIndex === 2) {
                    this.refs.contentDistribution.queryList(1);
                }
            });
            this.form.on('select(selectTypeCode)', (data) => {
                const typeCode = data.value;
                const nodeInfos = this.state.childCodeList;
                for (const i in nodeInfos) {
                    if (typeCode === nodeInfos[i].resourceType.type_code) {
                        if (nodeInfos[i].nodePrivateInfo && nodeInfos[i].nodePrivateInfo.aliases) {
                            this.state.inputValue.nodeAliase = nodeInfos[i].nodePrivateInfo.aliases;
                        } else {
                            this.state.inputValue.nodeAliase = nodeInfos[i].resourceType.type_name;
                        }
                        this.setState({
                            nodeInfo: nodeInfos[i]
                        }, () => {
                            //通知layui初始化完成,这里是在节点信息获取完成后在会掉
                            this.refs.contentRecorded.initComplete(nodeInfos[i]);
                            this.refs.contentList.layuiInitComplete();
                            this.refs.contentDistribution.layuiInitComplete();
                            if (this.state.tblIndex === 1) {
                                this.refs.contentList.queryList(1);
                            } else if (this.state.tblIndex === 2) {
                                this.refs.contentDistribution.queryList(1);
                            }
                        });
                        break;
                    }
                }
            });
        });
    }

    inputOnChange(e, index, inputValue) {
        inputValue[index] = e.target.value;
        this.setState({});
    }

    tabChange(layid, resource) {
        if (layid === 'tab1') {
            this.refs.contentRecorded.initComplete(this.state.nodeInfo, resource);
        }
        this.element.tabChange('mainTab', layid);
    }

    queryNodeInfo(typeCode) {
        let param = {};
        param.typeCode = typeCode;
        postJson("/cms/appResource/queryNodeInfo.x", $.param(param), (data) => {
            if (data.nodePrivateInfo && data.nodePrivateInfo.aliases) {
                this.state.inputValue.nodeAliase = data.nodePrivateInfo.aliases;
            } else {
                this.state.inputValue.nodeAliase = data.resourceType.type_name;
            }
            this.setState({
                nodeInfo: data
            }, function () {
                //通知layui初始化完成,这里是在节点信息获取完成后在会掉
                this.refs.contentRecorded.initComplete(data);
                this.refs.contentList.layuiInitComplete();
                this.refs.contentDistribution.layuiInitComplete();
            });
        });
    }

    showImage(url) {
        if (url) {
            layer.photos({
                photos: {
                    "title": "图片",
                    "data": [
                        {
                            "src": url
                        }
                    ]
                }, anim: 5
            });
        } else {
            layer.msg("此记录无照片!");
        }
    }

    submitTreatmentModal() {
        let index = layer.open({
            type: 1,
            shade: [0.8, '#393D49'],
            area: ['60%', 'auto'],
            title: false,
            minHeight: '80%',
            shadeClose: true,
            content: $('#modal_node_private_info'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定提交'],
            yes: () => {
                let param = {};
                param.typeCode = this.state.nodeInfo.resourceType.type_code;
                param.nodeAliase = this.refs.nodeAliase.value;
                param.unreadDefComm = this.refs.unreadDefComm.checked === true ? 0 : 1;
                if (param.nodeAliase.match(/^[ ]+$/)) {
                    layer.msg('节点别名不合法!', {icon: 5});
                    return;
                }
                for (const key in this.state.customSelectValue) {
                    this.state.customInputValue[key] = this.refs[key].value;
                }
                if (this.state.customInputValue) {
                    param.customProperty = JSON.stringify(this.state.customInputValue);
                }
                postJson("/cms/nodePrivateInfo/saveNodePrivateInfo.x", $.param(param), (data) => {
                    this.state.nodeInfo.nodePrivateInfo = data.data;
                    layer.msg('添加成功', {icon: 6});
                    layer.close(index);
                });
            }
        });
    }

    nodeOption() {
        if (this.state.childCodeList) {
            return this.state.childCodeList.map((array) => {
                let resourceType = array.resourceType;
                return (
                    <option
                        value={resourceType.type_code} data-commname={resourceType.type_name}>{resourceType.type_name}
                    </option>
                );
            });
        } else {
            return (
                <option value="-1">无</option>
            );
        }
    }

    spinnerView(spinnerMap, volue) {
        let newArry = [];
        if (spinnerMap) {
            for (let key in spinnerMap) {
                if (volue === key) {
                    newArry.push(<option value={key} selected={true}>{spinnerMap[key]}</option>)
                } else {
                    newArry.push(<option value={key}>{spinnerMap[key]}</option>)
                }
            }
        } else {
            newArry.push(<option value="-1">无</option>)
        }
        return newArry;
    }

    customAddPerms(customTypeList) {
        this.state.customSelectValue = {};
        this.state.customSelectValue = {};
        if (customTypeList) {
            return customTypeList.map((array) => {
                    return array.customContents.map((customContent) => {
                            let customProperty;
                            if (this.state.nodeInfo.nodePrivateInfo && this.state.nodeInfo.nodePrivateInfo.customProperty) {
                                customProperty = JSON.parse(this.state.nodeInfo.nodePrivateInfo.customProperty);
                            }
                            if (customContent.customType === 'CMS_CUSTOM_SORT') {
                                this.state.customSelectValue[customContent.customKey] = '';
                                for (const k in customProperty) {
                                    if (k === customContent.customKey) {
                                        this.state.customSelectValue[customContent.customKey] = customProperty[k];
                                        break;
                                    }
                                }
                                const volue = this.state.customSelectValue[customContent.customKey];
                                return (<div className="layui-form-item">
                                    <label className="layui-form-label">{customContent.customName}</label>
                                    <div className="layui-input-inline">
                                        <select ref={customContent.customKey}>
                                            {this.spinnerView(customContent.spinnerMap, volue)}
                                        </select>
                                    </div>
                                </div>);
                            } else {
                                for (const k in customProperty) {
                                    if (k === customContent.customKey && !this.state.customInputValue[k]) {
                                        this.state.customInputValue[k] = customProperty[k];
                                        break;
                                    }
                                }
                                return (<div className="layui-form-item">
                                        <label className="layui-form-label">{customContent.customName}</label>
                                        <div className="layui-input-block">
                                            <input id="customValues" ref={customContent.customKey}
                                                   value={this.state.customInputValue[customContent.customKey] ? this.state.customInputValue[customContent.customKey] : ''}
                                                   onChange={(e) => this.inputOnChange(e, customContent.customKey, this.state.customInputValue)}
                                                   placeholder={"请输入" + customContent.customName}
                                                   autoComplete="off" className="layui-input" type="text"/>
                                        </div>

                                    </div>
                                )
                            }
                        }
                    )
                }
            )
        }
    }

    render() {
        console.log('nodeInfo', this.state.nodeInfo.nodePrivateInfo);
        return <div className="box box-primary">
            <div className="box-frame">
                <div className="layui-form layui-form-pane">
                    <h1 style={{float: 'left', fontSize: 20}}>{this.state.inputValue.nodeAliase}</h1>
                    {this.isManyNode ? <div>
                        <label style={{marginLeft: '10px'}} className="layui-form-label">内容类型</label>
                        <div className="layui-input-inline" style={{float: 'left'}}>
                            <select name="selectTypeCode" ref="selectTypeCode" data-filter="selectTypeCode">
                                {this.nodeOption()}
                            </select>
                        </div>
                    </div> : ''}
                    <button className="layui-btn layui-btn-primary layui-btn-sm" type="button" style={{marginLeft: 5}}
                            onClick={() => this.submitTreatmentModal()}>自定义属性
                    </button>
                    <hr/>
                    <div className="layui-tab layui-tab-brief" data-filter="mainTab">
                        <ul className="layui-tab-title">
                            <li className="layui-this" data-id="tab1">内容录制</li>
                            <li data-id="tab2">内容列表</li>
                            <li data-id="tab3">内容分配</li>
                        </ul>
                        <div className="layui-tab-content">
                            <div className="layui-tab-item layui-show">
                                <ContentRecorded ref="contentRecorded"
                                                 showImage={(url) => this.showImage(url)}
                                                 isAdmin={this.isAdmin}/>
                            </div>
                            <div className="layui-tab-item">
                                <ContentList ref="contentList"
                                             tabChange={(layid, resource) => this.tabChange(layid, resource)}
                                             showImage={(url) => this.showImage(url)}
                                             nodeInfo={this.state.nodeInfo}
                                             isAdmin={this.isAdmin}/>
                            </div>
                            <div className="layui-tab-item">
                                <ContentDistribution ref="contentDistribution"
                                                     showImage={(url) => this.showImage(url)}
                                                     nodeInfo={this.state.nodeInfo}
                                                     isAdmin={this.isAdmin}/>
                            </div>
                        </div>
                    </div>

                    <div id="modal_node_private_info"
                         style={{
                             display: 'none',
                             paddingLeft: '10px',
                             paddingRight: '10px',
                             paddingTop: '20px'
                         }}
                         className="layui-form-item">

                        <div className="layui-form-item">
                            <div style={{float: 'left', marginTop: 6}}>
                                是否拉取默认小区资源
                            </div>
                            <div className="layui-input-block">
                                <input type="checkbox"
                                       name="open"
                                       data-skin="switch"
                                       data-text="ON|OFF"
                                       ref="unreadDefComm"
                                       checked={this.state.nodeInfo.nodePrivateInfo ? this.state.nodeInfo.nodePrivateInfo.unreadDefComm === 0 : true}/>
                            </div>
                        </div>

                        <div className="layui-form-item">
                            <label className="layui-form-label">别名</label>
                            <div className="layui-input-block">
                                <input name="nodeAliase" ref="nodeAliase" data-verify="nodeAliase"
                                       placeholder="请输入别名"
                                       autoComplete="off" className="layui-input" type="text"
                                       value={this.state.inputValue.nodeAliase}
                                       onChange={(e) => this.inputOnChange(e, 'nodeAliase', this.state.inputValue)}/>
                            </div>
                        </div>
                        {this.customAddPerms(this.state.nodeInfo.customPropertyList)}
                    </div>
                </div>
            </div>
        </div>
    }
}


ReactDOM.render(
    <AppView/>,
    document.getElementById('example')
);